package com.example.graduation.config.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * ProjectName graduation
 * shiro配置类
 *
 * @author xieyucan
 * <br>CreateDate 2022/2/14 14:53
 */
@Configuration
public class ShiroConfig {

    @Bean("securityManager")
    public SecurityManager securityManager(ShiroRealm shiroRealm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(shiroRealm);
        manager.setRememberMeManager(null);
        return manager;
    }


    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(ShiroFilter shiroFilter, SecurityManager securityManager) {
        /**
         * 将我的ShiroFilter，SecurityManager交由ShiroFilterFactoryBean管理
         */
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        Map<String, Filter> map = new HashMap<>();
        map.put("oauth2", shiroFilter);
        factoryBean.setFilters(map);

        LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
        hashMap.put("/webjars/**", "anon");
        hashMap.put("/druid/**", "anon");
        hashMap.put("/app/**", "anon");
        hashMap.put("/user/register", "anon");
        hashMap.put("/user/login", "anon");
        hashMap.put("/user/sendCode", "anon");
        hashMap.put("/user/emailLogin", "anon");
        hashMap.put("/user/anotherLogin", "anon");
        hashMap.put("/captcha.jpg", "anon");
        hashMap.put("/test/**", "anon");
        hashMap.put("/checkin/validCanCheckIn", "anon");
        hashMap.put("/**", "oauth2");
        factoryBean.setFilterChainDefinitionMap(hashMap);
        return factoryBean;
    }


    /**
     * 这个方法主要实现让shiro接受注解方法来实现鉴权
     *
     * @param securityManager
     * @return
     */
    @Bean("authorizationAttributeSourceAdvisor")
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }


    /**
     * shiro的生命周期
     *
     * @return
     */
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}
